package dbmgr

import (
	"cade/src/core/db"
	Err "cade/src/proto/errorcode"
	"time"
)

// ============================================================================

const (
	C_player_name_maxlen = 18
)

// ============================================================================

type UserInfo struct {
	UserId   string    `bson:"_id"`
	Name     string    `bson:"name"`
	IP       string    `bson:"ip"`
	CreateTs time.Time `bson:"cts"`
}

// ============================================================================

func Center_GetUserInfo(name string, on_create func(*UserInfo)) (int32, *UserInfo) {
	var obj UserInfo

	err := DBCenter.GetObjectByCond(
		C_tabname_userinfo,
		db.M{
			"name": name,
		},
		&obj,
	)
	if err == nil {
		// userinfo exists
		return Err.OK, &obj
	} else if db.IsNotFound(err) {
		// on create
		if on_create != nil {
			on_create(&obj)
		}

		// create new userinfo
		obj.UserId = Center_GenUserId()
		obj.Name = name
		obj.CreateTs = time.Now()

		// flush to db
		err = DBCenter.Insert(C_tabname_userinfo, &obj)
		if err == nil {
			// return new userinfo
			return Err.OK, &obj
		} else if db.IsDup(err) {
			return Err.Login_NameDup, nil
		} else {
			// failed
			return Err.Login_CreateUserInfo, nil
		}
	} else {
		// failed
		return Err.Failed, nil
	}
}
